package org.bspv.pharma.dao.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.bspv.pharma.dao.UserDAO;
import org.bspv.pharma.model.User;
import org.bspv.pharma.model.security.Credential;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * 
 * @author guillaume
 * 
 */

@Repository(value = "userDAO")
public class UserDAOImpl extends AbstractHibernateDAO<User, Long> implements
		UserDAO {

	@Autowired
	public UserDAOImpl(SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}

	@SuppressWarnings("unchecked")
	public List<Credential> getCredentials(User user) {
		DetachedCriteria crit = DetachedCriteria.forClass(Credential.class);
		crit.add(Restrictions.eq("user", user));
		return getHibernateTemplate().findByCriteria(crit);
	}

	@SuppressWarnings("unchecked")
	public List<Credential> getValidCredentials(User user) {
		Date today = Calendar.getInstance().getTime();
		DetachedCriteria crit = DetachedCriteria.forClass(Credential.class);
		crit.add(Restrictions.eq("user", user));
		crit.add(Restrictions.le("beginning", today));
		crit.add(Restrictions.ge("end", today));
		return getHibernateTemplate().findByCriteria(crit);
	}

}
